import type { DragEndEvent } from "@dnd-kit/core";
import { DndContext } from "@dnd-kit/core";
import { restrictToVerticalAxis,restrictToHorizontalAxis } from "@dnd-kit/modifiers";
import {
    arrayMove,
    SortableContext,
    useSortable,
    verticalListSortingStrategy,
    horizontalListSortingStrategy,/*垂直列表使用verticalListSortingStrategy,横向列表使用horizontalListSortingStrategy*/
} from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import * as React from "react";
import { searchVehicleDataAll } from "@/api";
import "./index.less";
import { useState, Dispatch, SetStateAction  } from "react";
import {Space,Card,Form,Input,Modal,Button,Row,Col,Spin,message, Flex, Tooltip} from "antd";
import {
  VehicleDataAll,
  Vehicle_color,
  UserProfileListItemVo,
  BluekeyDetailVo,
  BluekeyDetailVoList,
  UserProfileListItemVoList } from "@/types"
import {CompassTwoTone,SearchOutlined } from '@ant-design/icons';
import VehicleModal from "@/components/modal/vehicle";
import MyPagination, { PageInfo } from "@/components/pagination";

import MyTable from "@/components/table";
import { MapKey, ResponseUserInfo } from "@/types"

interface ItemType {
    id: number;
    dataA: VehicleDataAll;
    color: Vehicle_color;
}


interface DraggableListNodeProps extends ItemType {
  setId: Dispatch<SetStateAction<string | null>>;
  setShow: Dispatch<SetStateAction<boolean | null>>;
  }

const DraggableListNode = (props: DraggableListNodeProps  ) => {

            const showInfoModal = (id: string | null, type: boolean) => {
              console.log("id::"+JSON.stringify(id));
              if (id) {
                props.setId(id);
              } else {
                props.setId(null);
              }
              props.setShow(type);
            }


            const { attributes, listeners, setNodeRef, transform, transition } = useSortable({
                id: props.id,
            });

            
            const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {
              console.log("按钮ID:", event.currentTarget.id); // 输出按钮ID
            };

            const [activeTabKey2, setActiveTabKey2] = useState<string>("vehicle");
            const style = {
                transform: CSS.Transform.toString(transform),
                transition,
                marginTop: 8,
                height: '400px',
                overflow: 'auto'
            };


            const {
                    vehicleWithSimResp,
                    deviceVehicle,
                    msRemoteRelationVo,
                    rsMap,
                    simStatus,
                    vhlDataV2Vo,
                    userProfileListItemVoList,
                    bluekeyDetailVoList,
                    creditConfigStatusResp
                  } = props.dataA;
            
          const tabListNoTitle = [
            {
              key: 'vehicle',
              label: '车辆基础信息',
            },
            {
              key: 'bind',
              label: '人车关系',
            },
            {
              key: 'bluekey',
              label: '蓝牙钥匙',
            },
          ];
          const [isShow, setIsShow] = useState(true);
          const contentListNoTitle: { [key: string]: React.ReactNode } = {
            vehicle:  
            <div>
                <p>车辆VIN:   { vehicleWithSimResp?.vin ?            vehicleWithSimResp?.vin : '该vin未查询到车辆'}</p>
                <p>车机号:    { vehicleWithSimResp?.pdsn ?           vehicleWithSimResp?.pdsn : ''}</p>
                <p>tbox号:    { vehicleWithSimResp?.tbox ?           vehicleWithSimResp?.tbox : ''}</p>
                <p>iccid:     { vehicleWithSimResp?.iccid?           vehicleWithSimResp?.iccid : ''}</p>
                <p>imsi:      { vehicleWithSimResp?.imsi ?           vehicleWithSimResp?.imsi : ''}</p>
                <p>msisdn:    { vehicleWithSimResp?.msisdn ?         vehicleWithSimResp?.msisdn : ''}</p>
                <p>激活状态:   { deviceVehicle?.enrollStatusName ?    deviceVehicle?.enrollStatusName : ''}</p>
                <p>实名状态:   { deviceVehicle?.realNameStatusName ?  deviceVehicle?.realNameStatusName : ''}</p>
                <p>车辆类型:   { deviceVehicle?.vehicleTypeName ?     deviceVehicle?.vehicleTypeName : ''}</p>
                <p>网联类型:   { deviceVehicle?.carSptName ?          deviceVehicle?.carSptName : ''}</p>
                <p>门店名称:   { deviceVehicle?.enrollStatus ?        deviceVehicle?.enrollStatus : ''}</p>
                <p>车系代码:   { deviceVehicle?.seriesId ?            deviceVehicle?.seriesId : ''}</p>
                <p>车系中文:   { deviceVehicle?.seriesName ?          deviceVehicle?.seriesName : ''}</p>
                <p>车型编码:   { deviceVehicle?.styleId ?             deviceVehicle?.styleId : ''}</p>
                <p>销售时间:   { deviceVehicle?.availableDate ?       deviceVehicle?.availableDate : ''}</p>
                <p>车机版本:   { msRemoteRelationVo?.version ?        msRemoteRelationVo?.version : ''}</p>


                <p>剩余流量:   { rsMap?.monthUsedFlow    ? rsMap.monthUsedFlow    : '0.000'}MB</p>    
                <p>总流量:     { rsMap?.monthBalanceFlow ? rsMap.monthBalanceFlow : '0.000'}MB</p>    
                <p>卡在线状态: { simStatus? simStatus : ''}</p>

                <p className= { props.color?.ngtpCreateTime_isRed ? 'red-text' : 'black-text'}>
                   最后上报时间:   { props.dataA?.vhlDataV2Vo? vhlDataV2Vo.ngtpCreateTime : ''}</p>
               
                <p>一级车辆位置:   { props.dataA?.vhlDataV2Vo? vhlDataV2Vo.address : ''}</p>
                <p>二级车辆位置:   { props.dataA?.vhlDataV2Vo? vhlDataV2Vo.addressName : ''}</p>

                
                <p>是否授信车: { creditConfigStatusResp?.isCred=="1"  ? "是" : "否"}</p>
                <p style={{ display: isShow ? 'block' : 'none' }}>锁车状态:   { creditConfigStatusResp?.isCred=="1" && creditConfigStatusResp?.configStatus!=null  ? (creditConfigStatusResp?.configStatus==0? "已解锁": "未解锁"): ''}</p>
                <p style={{ display: isShow ? 'block' : 'none' }}>锁车时间:   { creditConfigStatusResp?.isCred=="1" && creditConfigStatusResp?.configTime!=null  ? creditConfigStatusResp?.configTime : ''}</p>
                {/* <p>授信单位:   { creditConfigStatusResp?.isCred && creditConfigStatusResp?.configStatus ? creditConfigStatusResp?.configStatus : ''}</p> */}


                
                <Tooltip title="search" style={{ display: 'inline-flex', alignItems: 'center' }}>
                    <p style={{ display: 'inline', margin: 0 }}>车机日志: </p>
                    <Button onClick={() => showInfoModal(vehicleWithSimResp?.vin ?? null, true)} shape="circle" id = {vehicleWithSimResp?.vin} icon={<SearchOutlined />} />
                </Tooltip>
                
                <Tooltip title="search" style={{ display: 'inline-flex', alignItems: 'center' }}>
                    <p style={{ display: 'inline', margin: 0 }}>手机日志: </p>
                    <Button onClick={() => showInfoModal(vehicleWithSimResp?.vin ?? null, true)} shape="circle" id = {vehicleWithSimResp?.vin} icon={<SearchOutlined />} />
                </Tooltip>
                <Tooltip title="search" style={{ display: 'inline-flex', alignItems: 'center' }}>
                    <p style={{ display: 'inline', margin: 0 }}>换件记录: </p>
                    <Button onClick={() => showInfoModal(vehicleWithSimResp?.vin ?? null, true)} shape="circle" id = {vehicleWithSimResp?.vin} icon={<SearchOutlined />} />
                </Tooltip>

            </div>,

            bind:
            userProfileListItemVoList?.map((user, index) => (
              <div key={index-1}>
                <p>userName:     {user && user.userName ? user.userName: '该vin未查询到用户'}</p>
                <p>昵称:         {user && user.nickName ? user.nickName: ''}</p>
                <p>uid:          {user && user.userAccountSid ? user.userAccountSid: ''}</p>
                <p>aid:          {user && user.userAccountBindId ? user.userAccountBindId: ''}</p>
                <p>mobilePhone:  {user && user.mobilePhone ? user.mobilePhone: ''}</p>
                <p>是否车主:      {user && user.relationshipType ? (user.relationshipType): ''}</p>
                <p>=======================</p>
              </div>
            ))
            ,

            bluekey: 
            bluekeyDetailVoList.map((key, index) => (
              <div key={index}>
                <p>id:                       {key && key.id ? key.id: ''}</p>
                <p>deviceId:                 {key && key.deviceId ? key.deviceId: '该vin无蓝牙钥匙'}</p>
                <p>userAccountSid:           {key && key.userAccountSid ? key.userAccountSid: ''}</p>
                <p>keyStatus:                {key && key.keyStatus ? key.keyStatus: ''}</p>
                <p>reationship:              {key && key.reationship ? key.reationship: ''}</p>
                <p>updatetime:               {key && key.updatetime ? key.updatetime: ''}</p>
                <p>endTime:                  {key && key.endTime ? key.endTime: ''}</p>
                <p>parkingKeyExpireTime:     {key && key.parkingKeyExpireTime ? key.parkingKeyExpireTime: ''}</p>
                <p>bluetoothProvider:        {key && key.bluetoothProvider ? key.bluetoothProvider: ''}</p>
                <p>=======================</p>
              </div>
            ))
            ,
          };

          const onTab2Change = (key: string) => {
            setActiveTabKey2(key);
          };

          return (
                    <Card
                      bordered 
                      style={style} 
                      tabList={tabListNoTitle}
                      hoverable={true}
                      activeTabKey={activeTabKey2}
                      onTabChange={onTab2Change}
                      tabProps={{size: 'middle',}}
                      //ref={setNodeRef} {...attributes} {...listeners}
                    > 
                    {contentListNoTitle[activeTabKey2]}
                    <div ref={setNodeRef}>
                        <CompassTwoTone {...listeners} {...attributes} />
                    </div>
                    </Card>
          );
};

function check_param(data :VehicleDataAll) {
      // 确保数组存在，若不存在则初始化为空数组
      data.bluekeyDetailVoList = data?.bluekeyDetailVoList || [];
      if(data?.bluekeyDetailVoList.length === 0){
        data.bluekeyDetailVoList = [];
        const newBluekeyDetail: BluekeyDetailVo = {
          id: 0,
          deviceId: "",
          userAccountSid: 0,
          keyStatus: 0,
          reationship: 0,
          updatetime: "",
          endTime: "",
          parkingKeyExpireTime: "",
          bluetoothProvider: ""
      };
      data?.bluekeyDetailVoList.push(newBluekeyDetail);
      }
  
      data.userProfileListItemVoList = data?.userProfileListItemVoList || [];
      if(data?.userProfileListItemVoList.length === 0){
        data.userProfileListItemVoList = [];
        const newUserProfile: UserProfileListItemVo = {
          userName: "该vin无车主信息",
          nickName: "",
          userAccountSid: "",
          userAccountBindId: 0,
          mobilePhone: "",
          avatar: "",
          relationshipType: "",
          sexuality: "",
          idNo: "",
          birthday: ""
      };
      data?.userProfileListItemVoList.push(newUserProfile);
      }
  return data;
}

export default function VehiclePage() {
  const [searchForm] = Form.useForm();
  const [vehicleData0,setVehicleData0] = useState<VehicleDataAll>();
  const [vehicleData1,setVehicleData1] = useState<VehicleDataAll>();
  const [vehicleData2,setVehicleData2] = useState<VehicleDataAll>();
  const [number_a,setNumber_a] = useState(0);
  const [isVehicle_color0, setVehicle_color0] = useState<Vehicle_color>();
  const [isVehicle_color1, setVehicle_color1] = useState<Vehicle_color>();
  const [isVehicle_color2, setVehicle_color2] = useState<Vehicle_color>();



  const [tableData, setData] = useState<ResponseUserInfo[]>([]);
  const [tableCol, setCol] = useState<MapKey>([]);
  const [total, setTotal] = useState(0);

  const [vin, setVin] = useState<string | null>(null);

  const data: ItemType[] = [
    //{ id: 1, dataA: vehicleData0 as VehicleDataAll },
    //{ id: 2, dataA: vehicleData1 as VehicleDataAll },
    //{ id: 3, dataA: vehicleData2 as VehicleDataAll },
    //{ id: 4, dataA: vehicleData  as VehicleDataAll},
  ];
  const [items, setItems] = useState(data);
 
  const onCancel = () => {
    setShow(false);
  };

  const submit = () => {
  };
  

  // 顶部搜索
  const searchVehicle = () => {
    let data = searchForm.getFieldsValue();
    // console.info ("searchVehicle: " + JSON.stringify(data));
    // console.info ("typeof(data): " + JSON.stringify(typeof(data)));
    // console.info ("Object.keys(data).length: " + Object.keys(data).length);

    if (!data || Object.keys(data).length === 0 || JSON.stringify(data) ==='{}') {
      console.info("searchVehicle: 空");
      return;
    }
    console.info("searchVehicleDataUrl开始执行::"+ JSON.stringify(data));
    searchVehicleDataUrl(data);
  };

  const handleDragEnd = ({ active, over }: DragEndEvent) => {
      console.log(active);
      console.log(over);
      if (active.id !== over?.id) {
          console.log("active", active.id);
          const activeIndex = items.findIndex((i) => i.id === active.id);
          const overIndex = items.findIndex((i) => i.id === over?.id);
          const newlist = arrayMove(items, activeIndex, overIndex);
          setItems(newlist);
      }
  };


  const set_color = (data: VehicleDataAll, vehicle_color:Vehicle_color) =>{
    if(data.vhlDataV2Vo?.ngtpCreateTime){
      const ngtpCreateTime_isRed = data.vhlDataV2Vo.ngtpCreateTime;
      if (new Date(ngtpCreateTime_isRed).getTime() < Date.now() - 2 * 3600 * 1000) 
        vehicle_color = { ngtpCreateTime_isRed: true };
       else 
        vehicle_color = { ngtpCreateTime_isRed: false };
    }
      return vehicle_color;
  }


  // 获取列表
  const searchVehicleDataUrl = 
    (data_param: string | null) => {
    searchVehicleDataAll(data_param).then((res) => {
      const { data, statusCode, statusMessage } = res;

     
      if (!data || Object.keys(data).length === 0 || JSON.stringify(data) ==='{}' || typeof data == 'string') {
        console.info("searchVehicle: 空");
        return;
      }

      console.info("searchVehicleDataAll::" + data);
      console.info("userProfileListItemVoList::" + JSON.stringify(data.userProfileListItemVoList));
      console.info("creditConfigStatusResp::"       + JSON.stringify(data.creditConfigStatusResp));
     // console.info("vhlDataV2Vo::"       + JSON.stringify(data.vhlDataV2Vo));
      
     check_param(data);
     setVin(data_param);

    console.info("外number" + number_a);
    let vehicle_color = { ngtpCreateTime_isRed: false };
    if( number_a === 0 ){
        setNumber_a(1);

        vehicle_color = set_color(data,vehicle_color);
        setVehicle_color0(vehicle_color);
        setVehicleData0(data);
        const dataB: ItemType[] = [
          { id: 1, dataA: data ,color: vehicle_color as Vehicle_color},
          //{ id: 2, dataA: vehicleData1 },
          //{ id: 3, dataA: vehicleData2 },
          //{ id: 4, dataA: vehicleData },
      ];
      setItems(dataB);

    } else if( number_a === 1 ){
        setNumber_a(2);
        
        
        vehicle_color = set_color(data,vehicle_color);
        setVehicle_color1(vehicle_color);
        setVehicleData1(data);
          const dataB: ItemType[] = [
            { id: 1, dataA: vehicleData0 as VehicleDataAll ,color: isVehicle_color0 as Vehicle_color},
            { id: 2, dataA: data ,color: vehicle_color as Vehicle_color},
            //{ id: 3, dataA: data },
            //{ id: 4, dataA: vehicleData },
        ];
        setItems(dataB);

    } else if( number_a === 2 ){
        setNumber_a(3);

        vehicle_color = set_color(data,vehicle_color);
        setVehicle_color2(vehicle_color);
        setVehicleData2(data);
          const dataB: ItemType[] = [
            { id: 1, dataA: vehicleData0 as VehicleDataAll ,color: isVehicle_color0 as Vehicle_color},
            { id: 2, dataA: vehicleData1 as VehicleDataAll ,color: isVehicle_color1 as Vehicle_color},
            { id: 3, dataA: data ,color: vehicle_color as Vehicle_color},
            //{ id: 4, dataA: vehicleData },
        ];
        setItems(dataB);
      

    }else {
      setNumber_a(1);
      console.info("内number" + number_a);

      setVehicleData0(data);
      const dataB: ItemType[] = [
        { id: 1, dataA: data ,color: vehicle_color as Vehicle_color},
        //{ id: 2, dataA: vehicleData1 },
        //{ id: 3, dataA: vehicleData2 },
        //{ id: 4, dataA: vehicleData },
    ];
    setItems(dataB);
    }

      console.info("外尾number" + number_a);
      return;
      });
  };

  const updateUserData = () => {
    //getUserData(pageData);
  }

const [chooseId, setId] = useState<string | null>(null);
const [showModal, setShow] = useState<boolean | null>(false);
const [pageData, setPage] = useState<PageInfo>({ page: 1 });

const showInfoModal = (id: string | null, type: boolean) => {
  console.log("id::"+JSON.stringify(id));
  if (id) {
    setId(id);
  } else {
    setId(null);
  }
  setShow(type);
}

return (
  <div className="vehicle-container">
  <Row gutter={24}>
    <Col span={24}>
        <div className="top-form">
            <Form layout="inline" form={searchForm}>
            
            <Form.Item name="vin"><Input placeholder="输入vin" /></Form.Item>
            
            <Button onClick={searchVehicle} type="primary" className="submit-btn">搜索</Button>

            <Button 
              onClick={() => {
                searchForm.resetFields();
                searchVehicle();
                }}>清空
            </Button>
            
            </Form>
        </div>
    </Col>

        <>
        <DndContext 
        //modifiers={[restrictToHorizontalAxis]} 
        onDragEnd={handleDragEnd}>
              <SortableContext 
              items={items.map((i: ItemType) => i.id)} 
              //strategy={horizontalListSortingStrategy}
              >
                      {items.map((item: ItemType) => (
                          <DraggableListNode key={item.id} {...item}  setId={setId} setShow={setShow}/>
                      ))}
              </SortableContext>
        </DndContext>
        </>
  </Row>

  <VehicleModal
        isShow={showModal}
        vin={chooseId}
        onCancel={showInfoModal}
        onOk={updateUserData}
      />
</div>

);
}


VehiclePage.route = {
  [MENU_PATH]: "/dfdev/vehicle",
};
